package com.xk.school_device.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xk.school_device.common.Result;
import com.xk.school_device.entity.Purchases;
import com.xk.school_device.entity.rep.ApproveReq;
import com.xk.school_device.service.IPurchasesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xk
 * @since 2025-04-16
 */
@RestController
@RequestMapping("/api/purchase")
public class PurchasesController {
    @Autowired
    private IPurchasesService purchasesService;

    /**
     * 申请采购名单
     */
    @PostMapping("/register")
    public Result register(@RequestBody Purchases purchases) {
        String id = String.valueOf(UUID.randomUUID());
        purchases.setPurchaseId(id);
         purchasesService.save(purchases);
        return Result.success("申请采购名单成功");
    }

    @PostMapping("/query")
    public Result query(@RequestBody Purchases purchases) {
        return Result.success(purchasesService.getPurchases(purchases));
    }
    @PostMapping("/update")
    public Result update(@RequestBody Purchases purchases) {
        purchasesService.updatePurchasesById(purchases);
        return Result.success("采购单更新成功");
    }
    @PostMapping("/delete/{id}")
    public Result delete(@PathVariable("id") String id) {
        purchasesService.deleteById(id);
        return Result.success("采购单删除成功");
    }

    @PostMapping("/findPendingApprovals")
    public Result findPendingApprovals(Purchases purchases) {
        String userId = StpUtil.getLoginIdAsString();
        return Result.success(purchasesService.findPendingApprovals(userId, purchases));
    }

    /**
     * 审批
     * @param approve
     * @return
     */
    @PostMapping("/approve")
    public Result approve(@RequestBody ApproveReq approve) {
        String userId = StpUtil.getLoginIdAsString();
        Purchases byId = purchasesService.getPurchaseById(approve.getPurchaseId());
        byId.setApproverId(userId);
        byId.setApprovalStatus(approve.getApprovalStatus());
        byId.setApprovalComment(approve.getApprovalComment());
        byId.setApprovalDate(LocalDateTime.now());
        purchasesService.updatePurchasesById(byId);
        return Result.success("审批成功");
    }



}
